<template>
	
	<el-dialog 
    class="upload-image-dialog" 
    center 
    width="65%" 
    :visible.sync="uploadVisible"
    @close="close">
		
		<!-- 自定义头部 -->
		<div slot="title" class="upload-dialog-title">
			<span class="dialog-header-nav-item" v-for="(nav,index) in uploadDialogNav" :key="index" :class="{'active':nav.current}" @click="dialogNavClick(index,nav,uploadDialogNav)">{{nav.name}}</span>
		</div>

		<!-- 内容区域 -->
		<div class="upload-dialog-content">

			<!-- 上传图片 -->
			<div v-show="dialogCurIndex == 0" class="upload-content-wrap">
				<!-- 上传图片组件 -->
				<div class="img-list" v-show="isUpload">
					<el-row :gutter="10">

						<!-- 上传图片容器 -->
						<el-col :span="6" v-for="(item,key) in uploadImgList" :key="key">

          			<div class="img-li-box">
            			<img class="img-li-b--url" :src="item.url">

            			<!-- 删除icon -->
            			<div class="img-li-b--delete">
              				<i @click="handleFileRemove(item,key)" class="el-icon-delete"></i>
            			</div>
          			</div>

						</el-col>

						<!-- 上传进度 -->
						<el-col :span="6">
          			<div v-if="!pass && progress !== 0" class="img-li-box img-li-b--progress">
            			<el-progress type="circle" :percentage="progress" :status.sync="proStatus"></el-progress>
          			</div>
        		</el-col>

        		<!-- 上传组件 -->
        		<el-col :span="6">  
          			<div class="img-upload-field">
            			<el-upload
              				with-credentials
              				class="img-upload-input"
              				:action="uploadUrl"
              				:data="uploadImgData"
              				accept="image/*"
              				list-type="picture-card"
              				:show-file-list="false"
              				multiple
              				:headers="uploadHeaders"
              				:on-change="uploadChange"
              				:on-success="upSuccess"
              				:on-progress="uploadOnProgress"
              				ref="upload"
            			>
              				<el-button ref="uploadBtn" id="uploadBtn" size="small" type="primary">点击上传</el-button>
            			</el-upload>
          			</div>
        		</el-col>


					</el-row>
				</div>

				<!-- 上传图片初始导航页 -->
				<div class="upload-select" v-show="!isUpload">
        		<div class="select-icon">
        			<i class="icon iconfont ipc-add-image"></i>
        		</div>
        		<div class="select-btn">
          		<el-button class="orange" type="primary" @click="uploadShow">选择图片</el-button>
        		</div>
        		<div class="select-tip">支持绝大多数图片格式，单张图片最大支持5MB</div>
      	</div>

			</div>

			<!-- 素材库 -->
			<div v-show="dialogCurIndex == 1" class="local-img-wrap">

				<!-- radio切换 -->
        <div class="nav-switch">
            
        		<el-radio-group v-model="localImgRadio" size="mini" @change="localImgRadioChange">
          			<el-radio-button label="全部"></el-radio-button>
          			<el-radio-button label="收藏"></el-radio-button>
        		</el-radio-group>

        		<div class="local-img-result">

          			<el-row :gutter="10" v-show="materials.length>0">
            			<el-col v-for="(item,index) in materials" :key="index" class="material-item-wrap" :span="6">
              
              				<div class="material-item" :class="{'selected':item.selected}" :data-sort="item.selectIndex !== undefined ? item.selectIndex : null" @click="materialItemClick(item,materials)">
                				<img :src="item.url">
              				</div>

            			</el-col>
          			</el-row>

        		</div>

        		<el-pagination
          			class="material-pagination"
          			background
          			small
          			layout="prev,pager,next"
          			:page-size="page.pageSize"
          			:current-page.sync="page.currentPage"
          			:total="page.total"
          			@current-change="materialPageChange"
        		></el-pagination>

        </div>

			</div>
		</div>

		<!-- 底部操作栏 -->
		<div slot="footer" class="upload-dialog-footer">
        	<!-- 上传图片按钮 -->
        	<div v-show="dialogCurIndex == 0">
          		<el-button type="danger" @click="closeModal">取消</el-button>
          		<el-button type="primary" @click="confirm('upload')">确认</el-button>
        	</div>
        
        	<!-- 素材库按钮 -->
        	<div v-show="dialogCurIndex == 1">
          		<el-button type="danger" @click="closeModal">取消</el-button>
          		<el-button type="primary" @click="confirm('material')">确认</el-button>
        	</div>
      	</div>
	</el-dialog>

</template>

<script>
import { 
  getMaterialList, 
  imgToArticle 
} from "@/api/substance/publish";

import { deepClone } from "@/utils/util";
import { baseUrl } from '@/config/env';
import { getToken } from '@/utils/auth';
import { validatenull } from '@/utils/validate'

//上传图片的url
const uploadUrl = baseUrl+'/rest/common/upload';
//获取图片的url
const imgPrefix = baseUrl+'/rest/common/preview/';

//素材图片的url
const materialPrefix = baseUrl+'/rest/material/image/preview/';


export default{
	props:{
		visible:{
			type:Boolean,
			default:false
		}
	},
	data(){
		return{
			//模态框显示隐藏
			uploadVisible:false,
			//模态框导航当前index
            dialogCurIndex:0,
			uploadDialogNav:[
				{name:'上传图片',value:1,current:true},
				{name:'素材库',value:2,current:false}
			],
			//图片上传地址
            uploadUrl:uploadUrl,
            //图片上传的参数
            uploadImgData:{form:'detail'},
            //服务器获取图片前缀
            imgPrefix:imgPrefix,
            materialPrefix:materialPrefix,
            //token头信息
            uploadHeaders:{'Authorization':'Bearer ' + getToken()},
			//是否启动上传图片模式
            isUpload:false,
            //上传进度
            progress:0,
            //是否上传成功
            pass:null,
            //上传图片列表容器
            uploadImgList: [],
            //素材库当前radio
            localImgRadio:'全部',
            //素材库图片展示列表
            materials:[],
            //素材库缓存列表
            materialsCache:{},
            //已选择的正文图片obj
            materialSelectCache:{},
            //已选择素材的当前索引
            materialSelectIndex:0,
			//素材库分页
			page: {
              pageSize: 8,
              currentPage: 1,
              total: 0
            },
            //上一次请求的页数
            materialsCacheKey:undefined
		}
	},
	watch:{
		visible(val){
			this.uploadVisible = val;
		}
	},
	computed:{
		//上传状态
      	proStatus(){
        	if(this.pass){
          		return 'success';
        	}else if(this.pass === false){
          		return 'exception';
        	}else{
          		return 'warning';
        	}
      	} 
	},
	methods:{
		//模态框头部导航切换
		dialogNavClick(index,nav,navs){
			if(index === this.dialogCurIndex){
      	return;
    	}
      //弹出离开当前页提示消息
      this.$confirm('切换图片选择菜单栏将清除当前操作图片, 请问是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         
          this.dialogCurIndex = index;
          for(var i=0;i<navs.length;i++){
            navs[i].current = (i===index ? true : false)
          }

          if(index == 0){
            //清空素材库图片选择
            this.resetMaterial();
          }
          //获取图片素材
          if(index == 1){
            //清空上传图片选择
            this.resetUpload();
            this.getMaterialList();
          }

        }).catch(() => {

          this.$message({
            type: 'info',
            message: '已取消切换'
          }); 

        });

    	
		},
		//显示上传组件和列表
        uploadShow(){
          	var uploadBtn = window.document.getElementById("uploadBtn");
          	uploadBtn.click();
        },
		//图片上传状态改变
		uploadChange(file,fileList){
          	console.log("--------图片上传状态改变-------------")
          	console.log(file);
          	if(file.status == 'ready'){
            	this.pass = null;
            	this.progress = 0;
            	//更改为上传状态
            	this.isUpload = true;
          	}else if(file.status == "fail"){
            	this.$message.error("图片上传出错，请刷新重试")
          	}
        },
        //图片上传进度
        uploadOnProgress(e,file){
          this.progress = Math.floor(e.percent);
        },
        //图片上传成功
        upSuccess(e,file,fileList){
          	console.log("--------获取上传成功-------------")
          	console.log(e);

          	this.pass = true;

          	var imgUrl = this.imgPrefix + e.data.fileId;
          	var fileId = e.data.fileId;
          	this.uploadImgList.push({
            	url:imgUrl,
            	selected:false,
            	fileId:fileId,
            	name:"新增图片"
          	})

        },
		//删除上传图片,从上传的图片列表移除，本地移除
        handleFileRemove(file,i){
          	if(!file.url){
            	return false
          	}

          	let that = this;
          	this.$confirm('是否删除此文件？', '提示', {
              	confirmButtonText: '确定',
              	cancelButtonText: '取消',
              	type: 'warning'
          	}).then(() => {
              	//可添加ajax
              	this.$message({
                  	type: 'success',
                  	message: '删除成功',
                  	onClose: () => {
                      	that.uploadImgList.splice(i, 1)
                  	}
              	})
          	}).catch((meg) => console.log(meg))

        },
        //素材库radio切换
        localImgRadioChange(value){
          	if(value == "全部"){
            	this.getMaterialList()
          	}else if(value == "收藏"){
            	this.getMaterialList(1)
          	}
        },
		//获取素材库图片
		getMaterialList(status){
			//查找一下缓存表里有没有
			var cacheKey = this.page.currentPage+'_'+status;
			if(this.materialsCache[cacheKey]){
				this.materials = this.materialsCache[cacheKey];
				//更新缓存列表key
      	this.materialsCacheKey = cacheKey;
      	return;
			}
			
			getMaterialList(this.page.currentPage,this.page.pageSize,status).then((res)=>{
            	console.log("----------素材库数据-----------")
            	console.log(res)
            	var material = res.data.data.records;
            	//设置总页数
            	this.page.total = res.data.data.total;
            	//添加图片url
            	this.materials = this.addUrlWithMaterial(material);

            	//更新缓存列表key
            	this.materialsCacheKey = cacheKey;
              this.materialsCache[this.materialsCacheKey] = this.materials;
          	})
		},
		//处理素材库原始数据，添加url
		addUrlWithMaterial(data){
          	var imgs = deepClone(data);
          	if(imgs.length > 0){
            	for(var i=0;i<imgs.length;i++){
              		imgs[i]["url"] = materialPrefix + imgs[i].fileId;
              		imgs[i]["selected"] = false;
            	}
          	}
          	return imgs;
        },
        //点击素材库每个图片
        materialItemClick(item,list){

        	//materialSelectCache
        	//判断是否被选中
        	if(item.selected === true){

        		//更新dom,循环缓存
        		if(!validatenull(this.materialsCache)){

        			for(var key in this.materialsCache){
        				var cacheItem = this.materialsCache[key];
        				for(var i=0;i<cacheItem.length;i++){
        					if(cacheItem[i]['selectIndex'] !== undefined && cacheItem[i]['selectIndex'] > item.selectIndex){
        						cacheItem[i]['selectIndex'] = Number(cacheItem[i]['selectIndex']) - 1;
        					}
        				}
        			}
        		}

        		
        		//已被选中，需要移除
        		delete this.materialSelectCache[item.fileId];
        		delete item["selectIndex"];
        		this.materialSelectIndex --;

        	}else{
        		//没有选中，需要添加
        		this.materialSelectIndex ++;
        		item["selectIndex"] = this.materialSelectIndex;
        		this.materialSelectCache[item.fileId] = item;
        	}



          item.selected = !item.selected;

          this.$forceUpdate();
        },
        //素材库分页页码改变
        materialPageChange(val){

          	if(this.localImgRadio == "全部"){
            	this.getMaterialList()
          	}else if(this.localImgRadio == "收藏"){
            	this.getMaterialList(1)
          	}
        },
        //取消通用设置
        closeBaseReset(){
        	//重置头部导航索引
        	this.dialogCurIndex = 0;
        	this.uploadDialogNav = [{name:'上传图片',value:1,current:true},{name:'素材库',value:2,current:false}];
        	//关闭模态框--当前组件
          	this.uploadVisible = false;
        },
        //重置上传
        resetUpload(){
        	this.uploadImgList = [];
            //清除upload组件
            this.$refs.upload.clearFiles();
            //重置上传引导页
            this.isUpload = false;
        },
        //重置素材库
        resetMaterial(){
            //上一次请求的页数
            this.materialsCacheKey = undefined;
        	  //清除已选素材缓存
        	  this.materialSelectCache = {};
          	//清除当前素材列表
          	this.materials = [];
          	//清楚素材列表缓存
          	this.materialsCache = {};
          	//重置已选择索引
          	this.materialSelectIndex = 0;
          	//重置素材分页
          	this.page = {pageSize: 8,currentPage: 1,total: 0}
        },
        //关闭模态框
        closeModal(){
        	//上传图片取消
          	if(this.dialogCurIndex == 0){
            	this.resetUpload();
          	}

          	//素材库取消
          	if(this.dialogCurIndex == 1){
          		this.resetMaterial();
          	}

          	this.closeBaseReset();
          	//通知父组件
          	this.$emit('close')
        },
        //关闭模态框
        close(){
          //上传图片取消
          this.resetUpload();
          //素材库取消
          this.resetMaterial();
          this.closeBaseReset();
          //通知父组件
          this.$emit('close')
        },
        //提交上传图片
        submitUploadImg(){
        	if(validatenull(this.uploadImgList)){
        		this.$ipcTips.warning('请上传正文图片')
        		return false;
        	}
        	return this.uploadImgList; 
        },
        //提交素材图片
        submitMaterialImg(){
        	if(validatenull(this.materialSelectCache)){
            this.$ipcTips.warning('请选择素材图片')
        		return false;
        	};
        	var select_img_arr = [];
        	for(var key in this.materialSelectCache){
        		select_img_arr.push(this.materialSelectCache[key]);
        	}
          
        	return select_img_arr;

        },
        //模态框确认
        confirm(type){
        	var selectImg = null;
        	if(type == 'upload'){
        		selectImg = this.submitUploadImg();
        	}

        	if(type == 'material'){
        		selectImg = this.submitMaterialImg();
        	}


        	if(selectImg === false) {
            return false
          };

          console.log("%cuploadDialog组件选择的正文图片","background:#f3c;color:#fff")
          console.log(selectImg)

          var selectImgIds = [];
          //对选中的图片进行提取，只需要传递fileId
          for(var i=0;i<selectImg.length;i++){
            selectImgIds.push(selectImg[i].fileId)
          }


          if(type == 'upload'){
            //通知父组件确认
            this.$emit('confirm',selectImgIds)

            this.resetUpload();
            this.resetMaterial();

          }else if(type == 'material'){
            //请求接口将素材库图片添加到文章
            imgToArticle(selectImgIds).then((res)=>{
              console.log("-----素材库图片添加到文章返回结果------")
              console.log(res)
              var imgs = res.data.data;
              //通知父组件确认
              this.$emit('confirm',imgs)
              this.resetUpload();
              this.resetMaterial();

            })
          }
        	
        },
        
	}
}

</script>

<style>
	.upload-image-dialog .el-dialog{
		margin-bottom: 15vh;
	}
</style>


<style scoped>

/*上传图片模态框*/
.upload-dialog-title{
    text-align: left;
}
.dialog-header-nav-item{
    padding: 10px 20px;
    cursor: pointer;
}
.dialog-header-nav-item:hover{
    color: #ff8100;
}
.dialog-header-nav-item.active{
    color: #ff8100;
}
.upload-dialog-content{
    min-height: 400px;
}
.upload-select{
    padding: 100px 0;
    text-align: center;
}
.upload-select .select-icon i{
    font-size: 50px;
    color: #c3c3c3;
}
.upload-select .select-btn{
    padding: 15px 0;
}
.upload-select .select-tip{
    color: #999999;
}

.local-img-result{
    margin-top: 5px;
}

/*素材库图片列表*/
.material-item{
    min-height:180px;
    padding: 5px;
    margin-bottom: 5px;
    border:1px solid #999;
    position: relative;
}
.material-item.selected:before{
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    background-color: rgba(0,0,0,.5);
    background-image: url();
    -moz-background-size: 40px 40px;
    background-size: 40px 40px;
    background-position: 100% 0;
    background-repeat: no-repeat;
    text-align: center;
    color: #fffacd;
}

.material-item.selected:after {
    content: attr(data-sort);
    display: block;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    z-index: 1001;
    font-size: 30px;
    color: #fffacd;
}
.material-item:hover{
    border-color:#ff8406;
}
.material-item>img{
    width:100%;
    max-height: 160px;
}

.material-pagination{
    text-align: right;
}


</style>

<style lang="scss" scoped>



.img-list {
  	overflow: hidden;
  	width: 100%;
  	// 文件列表
  	.img-li-box {
      	float: left;
      	text-align: left;
      	position: relative;
      	display: inline-block;
      	width: 100%;
      	height: 180px;
      	padding: 5px;
      	margin-bottom: 10px;
      	border: 1px solid #d1dbe5;
      	border-radius: 4px;
      	transition: all .3s;
      	box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .12), 0 0 6px 0 rgba(0, 0, 0, .04);
      	// 图片
      	.img-li-b--url {
          	display: block;
          	width: 100%;
          	height: 140px;
          	margin: 0 auto;
          	border-radius: 4px;
      	}
      	// 底部
      	.img-li-b--bottom {
          	margin-top: 10px;
          	// 名称
          	.img-li-b--name {
              	width: 90%;
              	text-overflow: ellipsis;
              	overflow: hidden;
              	height: 25px;
              	line-height: 25px;
          	}
      	}
      	// 删除按钮
      	.img-li-b--delete {
          	position: absolute;
          	bottom: 10px;
          	right: 10px;
          	color: #8492a6;
          	cursor: pointer;
          	font-size: 1.1em;
      	}
      	// 放大遮罩层
      	.img-li-b--layer {
          	position: absolute;
          	left: 0;
          	right: 0;
          	top: 0;
          	height: 200px;
          	color: #fff;
          	text-align: center;
          	z-index: 5;
          	background-color: rgba(0, 0, 0, .4);
          	// 放大按钮
          	i {
              	font-size: 1.6em;
              	margin-top: 80px;
          	}
      	}
      	.img-li-b--delete,
      	.img-li-b--layer {
          	opacity: 0;
          	transition: all .3s;
      	}
      	// 悬浮可见删除 or 放大按钮
      	&:hover {
          	.img-li-b--delete,
          	.img-li-b--layer {
              	opacity: 1;
	        }
	    }
      	// 上传进度
      	&.img-li-b--progress {
          	text-align: center;
          	padding-top: 20px;
      	}
  	}
    // 上传按钮
    .img-upload-field {
        width: 100%;
        height: 180px;
        display: table;
        text-align: center;
        .img-upload-input{
            width: 100%;
            height: 100%;
            display: table-cell;
            
        }
    }
}
</style>